package com.zkhz.base.handler;


import com.zkhz.base.common.dto.ResponseDTO;
import com.zkhz.base.constant.enums.ErrorStatus;
import com.zkhz.base.exception.BusinessException;
import com.zkhz.base.exception.BusinessValidException;
import com.zkhz.base.util.system.I18nUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * @Description 统一异常处理
 *
 * @author wuzeqin
 * @date 2020/5/18
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BusinessValidException.class)
    public ResponseDTO<Void> businessValidException(BusinessValidException ex) {
        log.error(ex.getMessage(), ex);
        return ResponseDTO.status(ex.getStatus()).message(ex.getMessage()).build();
    }

    @ExceptionHandler(value = BusinessException.class)
    public ResponseDTO<Void> businessException(BusinessException ex, HttpServletResponse response) {
        log.debug(ex.getMessage(), ex);
        response.setStatus(HttpServletResponse.SC_OK);
        return ResponseDTO.status(ex.getStatus()).message(ex.getMessage()).build();
    }

    @ExceptionHandler(value = RuntimeException.class)
    public ResponseDTO<Void> Exception(RuntimeException ex) {
        log.error(ex.getMessage(), ex);
        String message = ex.getMessage();
        return ResponseDTO.status(ErrorStatus.B0001).message(I18nUtil.isChinese(message) ? message : "网络异常，请稍后再试").build();
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseDTO<Void> Exception(Exception ex) {
        log.error(ex.getMessage(), ex);
        String message = ex.getMessage();
        return ResponseDTO.status(ErrorStatus.B0001).message(I18nUtil.isChinese(message) ? message : "网络异常，请稍后再试").build();
    }
}
